package com.bank.service.impl;

import com.bank.constant.MessageConstant;
import com.bank.dto.UserDTO;
import com.bank.dto.UserLoginDTO;
import com.bank.dto.UserUpdateInfoDTO;
import com.bank.entity.User;
import com.bank.exception.UserNotFoundException;
import com.bank.exception.PasswordErrorException;
import com.bank.mapper.UserMapper;
import com.bank.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 员工登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new UserNotFoundException(MessageConstant.USER_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return user;
    }

    @Transactional
    @Override
    public void register(UserDTO userDTO) {
        User user = new User();

        // 对象属性赋值
        BeanUtils.copyProperties(userDTO, user);

        // 密码加密
        user.setPassword( DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));

        // 保存到数据库
        userMapper.insert(user);
    }

    @Transactional
    @Override
    public void update(UserUpdateInfoDTO userUpdateInfoDTO) {
        if (userUpdateInfoDTO.getPassword() != null) {
            // 密码加密
            userUpdateInfoDTO.setPassword(DigestUtils.md5DigestAsHex(userUpdateInfoDTO.getPassword().getBytes()));
        }

        // 更新数据库
        userMapper.update(userUpdateInfoDTO);
    }

    @Override
    public User getUserById(Long userId) {
        return userMapper.getById(userId);
    }
}
